import { type Reactive, toRaw, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';

/**
 * 创建一个带防抖的 ref
 * @param initialValue 初始值
 * @param delay 防抖延时 (ms)
 * @returns 返回 source 和 debounced 两个 ref
 */
export function useDebounceRef<T extends {}>(initialValue: T, delay = 300): [Reactive<T>, Ref<T>] {
    const source = reactive<T>(initialValue);
    const debounced = ref<T>(initialValue) as Ref<T>;

    const updater = useDebounceFn((val: T) => {
        debounced.value = val;
    }, delay);

    watch(source, value => {
        updater(toRaw(value) as T);
    });

    watch(debounced, value => {
        console.log('防抖后的值', value);
    });

    return [source, debounced];
}
